//
//  WorkingTableController.m
//  Recycling
//
//  Created by jzd on 2018/5/21.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "WorkingTableController.h"
#import "WorkingTableViewCell.h"
#import "SureCompleteVC.h"//完成订单
#import "roteNavgationController.h"//导航
#import "orderDetailVC.h"//详情
#import "orderModel.h"
#import "selectDateVC.h"
#import "transitionAnnimater.h"

@interface WorkingTableController ()
@property(assign,nonatomic)int page;
@property(strong,nonatomic)NSMutableArray *dataArray;
@property(strong,nonatomic)NSMutableArray *oneArray;
@property(strong,nonatomic)NSMutableArray *twoArray;
@property(assign,nonatomic)int total;
@property (strong,nonatomic)transitionAnnimater *animater;

@property(assign,nonatomic)int firstTotal;
@property(assign,nonatomic)int secondTotal;


@property (assign,nonatomic) BOOL firstButSelect;
@property (assign,nonatomic) BOOL secondButSelect;

@end

@implementation WorkingTableController
static NSString *const identifier = @"WorkingTableViewCell";
-(transitionAnnimater *)animator{
    if (_animater == nil) {
        _animater = [[transitionAnnimater alloc]init];
        _animater.torect = CGRectMake(20, SJScreenH*0.5-157, SJScreenW-40, 314);
    }
    return _animater;
}
-(NSMutableArray *)oneArray{
    if (!_oneArray) {
        _oneArray = [NSMutableArray array];
    }
    return _oneArray;
}
-(NSMutableArray *)twoArray{
    if (!_twoArray) {
        _twoArray = [NSMutableArray array];
    }
    return _twoArray;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        [_dataArray addObject:self.oneArray];
        [_dataArray addObject:self.twoArray];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(238.0, 238.0, 238.0, 1.0);
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(titleViewH+statsBarHeight+NavgationBarH, 0, self.tabBarController.tabBar.height, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WorkingTableViewCell class]) bundle:nil] forCellReuseIdentifier:identifier];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;

    
    //点击完単
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(compelete:) name:completeNotification object:nil];
    //监听预约
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reservation:) name:reservationNotification object:nil];
    //位置被点击
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addressOnClick:) name:addressOnClickNotification object:nil];
    
    //有新的订单
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestAllData) name:jiedanNotification object:nil];
    
    self.tableView.mj_header = [SJRefresh headerWithRefreshingTarget:self refreshingAction:@selector(requestAllData)];
    [self.tableView.mj_header beginRefreshing];

    
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData:)];
    
//    [self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//
//    UIView *vv = [self tableView:self.tableView viewForHeaderInSection:0];
//    UILabel *lab = [vv viewWithTag:666];
//    lab.text = [NSString stringWithFormat:@"今日的订单:%zd",self.oneArray.count];
//
//    UIView *vvK = [self tableView:self.tableView viewForHeaderInSection:0];
//    UILabel *labK = [vvK viewWithTag:667];
//    labK.text = [NSString stringWithFormat:@"以后的订单:%zd",self.twoArray.count];
//
//}
-(void)requestAllData{
    
    [self requestOneData:1];
    
}

-(void)requestTwoData:(int)daytype{
    self.page = 1;
    
    //040001002：待接单
    //040001003：进行中
    //040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(self.page),
                             @"limit" : @(1000),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001003",
                             @"daytype":@(daytype)
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            NSString *msg = [responseObject objectForKey:@"ErrorMessage"];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    
                    self.secondTotal = [[data objectForKey:@"total"] intValue];
                    self.total = self.firstTotal + self.secondTotal;
                    
                    NSArray *arr = [orderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"rows"]];
                    if (arr.count != 0) {
                        self.twoArray = arr.mutableCopy;
                    }else{
                        [self.twoArray removeAllObjects];
                        [self.tableView.mj_header endRefreshing];
                    }
                    
                }else{
                    [self.twoArray removeAllObjects];
                }
            }else{
                [self.navigationController.view showToast:msg completion:nil];
            }
        }
        [self.tableView.mj_header endRefreshing];
        
        NSMutableArray *arr1 = [NSMutableArray array];
        NSMutableArray *arr2 = [NSMutableArray array];
        [self.dataArray replaceObjectAtIndex:0 withObject:arr1];
        [self.dataArray replaceObjectAtIndex:1 withObject:arr2];
        self.firstButSelect = NO;
        self.secondButSelect = NO;
        [self.tableView reloadData];
        
    }];
}
-(void)requestOneData:(int)daytype{
    self.page = 1;
    
    //040001002：待接单
    //040001003：进行中
    //040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(self.page),
                             @"limit" : @(1000),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001003",
                             @"daytype":@(daytype)
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            NSString *msg = [responseObject objectForKey:@"ErrorMessage"];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    
                    self.firstTotal = [[data objectForKey:@"total"] intValue];
                    NSArray *arr = [orderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"rows"]];
                    if (arr.count != 0) {
                        self.oneArray = arr.mutableCopy;
                    }else{
                        [self.oneArray removeAllObjects];
                        [self.tableView.mj_header endRefreshing];
                    }
                    
                }else{
                    [self.oneArray removeAllObjects];
                }
            }else{
                [self.navigationController.view showToast:msg completion:nil];
            }
        }
        
        [self requestTwoData:2];
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)requestMoreData:(int)daytype{
    self.page ++;
    //040001002：待接单
    //040001003：进行中
    //040001004：已完工
    
    NSDictionary *params = @{
                             @"pageno":@(self.page),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001002"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            NSString *msg = [responseObject objectForKey:@"ErrorMessage"];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    
                    int total = [[data objectForKey:@"total"] intValue];
                    if (total<pageNum) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    NSArray *arr = [orderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"rows"]];
                    if (arr.count != 0) {
                        [self.dataArray addObjectsFromArray:arr];
                    }else{
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                        [self.navigationController.view showToast:@"没有更多数据" completion:nil];
                        return ;
                    }
                    
                }else{
                    [self.navigationController.view showToast:@"暂无数据" completion:nil];
                }
            }else{
                [self.navigationController.view showToast:msg completion:nil];
            }
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(void)compelete:(NSNotification *)noti{
    
    SureCompleteVC *vc = [[SureCompleteVC alloc]init];
    vc.model = noti.object;
    __block __weak typeof (self) Copy_Self = self;
    vc.refreshBlock = ^(BOOL isSuccess) {
        [Copy_Self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)reservation:(NSNotification *)noti{
    selectDateVC *vc = [[selectDateVC alloc]init];
    vc.modalPresentationStyle = UIModalPresentationCustom;
    vc.transitioningDelegate  = self.animator;
    self.animator.torect = CGRectMake(0, SJScreenH-260, SJScreenW, 260);
    vc.datePickerMode = UIDatePickerModeDateAndTime;
    vc.minDate = [NSDate date];
    __block __weak WorkingTableController *copy_self = self;
    vc.dateBlock = ^(NSString *date) {
        [copy_self replaceTime:date AndModel:noti.object];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
-(void)replaceTime:(NSString *)time AndModel:(orderModel *)model{
    NSDictionary *params = @{@"id":@(model.ID),
                             @"uid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"applydate":time
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:changeApplyTime parameters:params method:POST callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            if (code == 1) {
                [self.tableView.mj_header beginRefreshing];
                [self.navigationController.view showToast:@"修改预约时间成功" completion:nil];
            }else{
                [self.navigationController.view showToast:@"修改预约时间失败" completion:nil];
            }
        }
    }];
}
-(void)addressOnClick:(NSNotification *)noti{
    if ([noti.object isKindOfClass:[WorkingTableViewCell class]]) {
        WorkingTableViewCell *cell = noti.object;
    roteNavgationController *vc = [[roteNavgationController alloc]init];
        vc.goAddressStr = cell.model.UserAddress;
    [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
//    [self removeObserver:self forKeyPath:@"dataArray"];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = [self.dataArray objectAtIndex:section];
    
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *arr = [self.dataArray objectAtIndex:indexPath.section];
    
    orderModel *model = [arr objectAtIndex:indexPath.row];
    WorkingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 220;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;//35
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SJScreenW, 35)];
        header.backgroundColor = [UIColor whiteColor];
        
        
        UIButton *imgBut = [UIButton buttonWithType:UIButtonTypeCustom];
        imgBut.frame = CGRectMake(5, 9, 17, 17);
        imgBut.tag = 999;
        [imgBut setImage:[UIImage imageNamed:@"icon_arrow_down"] forState:UIControlStateSelected];
        [imgBut setImage:[UIImage imageNamed:@"icon_arrow_right"] forState:UIControlStateNormal];
        [header addSubview:imgBut];
        
        UILabel *headeTitle = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, SJScreenW-34, 35)];
        headeTitle.backgroundColor = [UIColor whiteColor];
        NSString *num = @"";
        imgBut.selected = self.firstButSelect;
        num = [NSString stringWithFormat:@"今日的订单:%zd",self.firstTotal];
        headeTitle.text = num;
        headeTitle.tag = 666;
        headeTitle.font = [UIFont systemFontOfSize:15];
        [header addSubview:headeTitle];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"" forState:UIControlStateNormal];
        button.tag = 100+section;
        button.selected = NO;
        [button addTarget:self action:@selector(headerTitleOnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = header.frame;
        [header addSubview:button];
        
        return header;
    }else{
        UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SJScreenW, 35)];
        header.backgroundColor = [UIColor whiteColor];
        
        
        UIButton *imgBut = [UIButton buttonWithType:UIButtonTypeCustom];
        imgBut.frame = CGRectMake(5, 9, 17, 17);
        imgBut.tag = 999;
        [imgBut setImage:[UIImage imageNamed:@"icon_arrow_down"] forState:UIControlStateSelected];
        [imgBut setImage:[UIImage imageNamed:@"icon_arrow_right"] forState:UIControlStateNormal];
        [header addSubview:imgBut];
        
        UILabel *headeTitle = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, SJScreenW-34, 35)];
        headeTitle.backgroundColor = [UIColor whiteColor];
        NSString *num = @"";
        imgBut.selected = self.secondButSelect;
        num = [NSString stringWithFormat:@"以后的订单:%zd",self.secondTotal];
        headeTitle.text = num;
        headeTitle.tag = 667;
        headeTitle.font = [UIFont systemFontOfSize:15];
        [header addSubview:headeTitle];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"" forState:UIControlStateNormal];
        button.tag = 100+section;
        button.selected = NO;
        [button addTarget:self action:@selector(headerTitleOnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = header.frame;
        [header addSubview:button];
        
        return header;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *arr = [self.dataArray objectAtIndex:indexPath.section];
    
    orderModel *model = [arr objectAtIndex:indexPath.row];
    orderDetailVC *vc = [[orderDetailVC alloc]init];
    vc.model = model;
    __block __weak WorkingTableController * Copy_Self = self;
    vc.isRefreshView = ^(BOOL isNeed) {
        __strong typeof (Copy_Self) strongSelf = Copy_Self;
        if (isNeed) {
            [strongSelf.tableView.mj_header beginRefreshing];
        }
    };
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)headerTitleOnClick:(UIButton *)headerBut{

    
    if (headerBut.tag == 100) {
        self.firstButSelect = ! self.firstButSelect;
        //今日
        if (self.firstButSelect) {
            [self.dataArray replaceObjectAtIndex:0 withObject:self.oneArray];
        }else{
            NSMutableArray *arr = [NSMutableArray array];
            [self.dataArray replaceObjectAtIndex:0 withObject:arr];
        }

        [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        //以后

        self.secondButSelect = ! self.secondButSelect;
        if (self.secondButSelect) {
            [self.dataArray replaceObjectAtIndex:1 withObject:self.twoArray];
        }else{
            NSMutableArray *arr = [NSMutableArray array];
            [self.dataArray replaceObjectAtIndex:1 withObject:arr];
        }
        
        [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }
    
}
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
//
//    return [UIImage imageNamed:@"empty"];
//
//}
//- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
//    NSLog(@"空白页点击事件");
//    //重新加载默认的数据
//    [self.tableView.mj_header beginRefreshing];
//}
//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
//
//    NSString *text = @"没有相关数据";
//
//    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f], NSForegroundColorAttributeName: TITLECOLOR};
//    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
//
//}
//- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView{
//
//    NSString *text = @"重新加载";
//
//    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new]; paragraph.lineBreakMode = NSLineBreakByWordWrapping;
//
//    paragraph.alignment = NSTextAlignmentCenter;
//
//    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: TITLECOLOR, NSParagraphStyleAttributeName: paragraph}; return [[NSAttributedString alloc] initWithString:text attributes:attributes];
//
//}
@end
